<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/滚动条事件.css">
</head>
<body>
    <div class="box">
    </div>
    <div class="nav"></div>
    <script>
        var now = 0;
        var nav = document.querySelector(".nav");
        var box = document.querySelector(".box");
        for(var i = 0;i<5;i++){
            var div = document.createElement("div");
            div.classList.add("item");
            div.setAttribute("id",`item${i}`);
            div.style.opacity = Math.random().toFixed(1);
            var height = Math.floor(Math.random()*800);
            while (height<400) height = Math.floor(Math.random()*800);
            div.style.height = height+"px";
            box.appendChild(div);
            var navItem = document.createElement("a");
            navItem.classList.add("navItem");
            navItem.textContent = `item${i}`;
            navItem.href = `#item${i}`;
            nav.appendChild(navItem);
            if(i==0)navItem.classList.add("active");
            navItem.onclick = function(){
                document.querySelector(".active").classList.remove("active");
                this.classList.add("active");
            }
        }
        window.onscroll = function(e){
            var navItems = document.querySelectorAll(".navItem");
            var items = document.querySelectorAll(".item")
            var top = document.documentElement.scrollTop;
            for(var i = 0;i<items.length;i++){
                if(items[i].offsetTop+parseInt(getComputedStyle(items[i],null).height)>=top){
                    if(now==i)break;
                    now = i;
                    console.log(navItems[i]);
                    console.log(navItems[i].offsetTop,top);
                    document.querySelector(".active").classList.remove("active");
                    navItems[i].classList.add("active");
                    break;
                }
            }
        }
    </script>
</body>
</html>